package com.chrilwe.pigpig.auth.service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.chrilwe.pigpig.auth.common.PhoneConfigProperty;
import com.chrilwe.pigpig.auth.common.request.PhoneLoginRequest;
import com.chrilwe.pigpig.auth.common.response.LoginResult;
import com.chrilwe.pigpig.auth.common.response.ResultEnum;

/**
 * 手机短信服务
 * 
 * @author chrilwe 2020-8-24
 */
@Service
public class PhoneService {

	@Autowired
	protected StringRedisTemplate stringRedisTemplate;

	@Autowired
	protected ValidateCodeService validateCodeService;

	@Autowired
	protected IAcsClient acsClient;

	@Autowired
	protected PhoneConfigProperty phoneConfigProperty;

	public LoginResult phoneLogin(PhoneLoginRequest request) {
		if (request != null) {
			String clientToken = request.getClientToken();
			String phone = request.getPhone();
			String phoneCode = request.getPhoneCode();
			String validateCode = request.getValidateCode();

			if (StringUtils.isAnyEmpty(clientToken, phone, phoneCode, validateCode)) {
				return new LoginResult(ResultEnum.ERROR_REQUEST_PARAM.getCode(),
						ResultEnum.ERROR_REQUEST_PARAM.getName(), "");
			}
			
			boolean checkCode1 = validateCodeService.checkCode(clientToken, validateCode);
			boolean checkCode2 = checkPhoneCode(phone, phoneCode);
			if(!(checkCode1 && checkCode2)) {
				return new LoginResult(ResultEnum.ERR_VALIDATE_CODE.getCode(), ResultEnum.ERR_VALIDATE_CODE.getName(), "");
			}
			
			doLogin(phone);
		}
		return new LoginResult(ResultEnum.ERROR_REQUEST_PARAM.getCode(),
				ResultEnum.ERROR_REQUEST_PARAM.getName(), "");
	}
	
	protected void doLogin(String phone) {
		
	}

	public boolean doSendPhoneCode(String phone) {
		String phoneCode = generateRandomPhoneCode();
		SendSmsRequest request = new SendSmsRequest();
		request.setMethod(MethodType.POST);
		request.setPhoneNumbers(phone);
		request.setSignName(phoneConfigProperty.getSignName());
		request.setTemplateCode(phoneConfigProperty.getTemplateCode());
		request.setTemplateParam("{\"code\":\""+phoneCode+"\"}");
		request.setOutId(phone);

		SendSmsResponse sendSmsResponse = null;
		try {
			sendSmsResponse = acsClient.getAcsResponse(request);
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			saveTmpPhoneCode(phoneCode, phone);
			return true;
		}
		return false;
	}

	// 随机生成6位验证码
	private String generateRandomPhoneCode() {
		Random random = new Random();
		String code = "";
		for (int i = 0; i < 6; i++) {
			int j = random.nextInt(9);
			code += j;
		}
		return code;
	}
	
	//临时存放验证码5分钟后失效
	private void saveTmpPhoneCode(String phoneCode, String phone) {
		String PHONECODE = "phone_code_";
		stringRedisTemplate.opsForValue().set(PHONECODE+phone, phoneCode, phoneConfigProperty.getPhoneCodeExpire(), TimeUnit.MINUTES);
	}

	private boolean checkPhoneCode(String phone, String code) {
		String PHONECODE = "phone_code_";
		String s = stringRedisTemplate.opsForValue().get(PHONECODE+phone);
		if(StringUtils.isEmpty(s)) {
			return false;
		}
		if(!code.equals(s)) {
			return false;
		}
		return true;
	}

}
